package com.smart.order.biz.service.impl;

import com.smart.order.biz.common.dto.OrderDTO;
import com.smart.order.biz.feign.CartsService;
import com.smart.order.biz.service.OrderBizService;
import com.smart.order.constants.OrderConstants;
import com.smart.order.dto.CartsDTO;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author Administrator
 * 1. 创建订单
 * 2. 更新库存
 * 3. 订单支付
 */
@Service
@Slf4j
public class OrderBizServiceImpl implements OrderBizService {

    @Resource
    private CartsService cartsService;

    @Resource
    private RocketMQTemplate rocketMQTemplate;

    @Override
    public String creatOrder(OrderDTO orderDTO) {
        List<CartsDTO> cartsList = cartsService.list(orderDTO.getCartIds()).getData();
        String orderSn = "123456";

        // 生成订单号
        //  通过购物车ID查询商品信息
        // 更新库存信 0
        // 计算 总金额  支付金额  优惠金额
        // 删除购物车
        // 自动取消订单
        // 保存订单信息 订单详情
        cartsService.batchDel(orderDTO.getCartIds());
        //取消订单
        rocketMQTemplate.asyncSend(OrderConstants.OrderTopic.ORDER_CANCEL_TOPIC, MessageBuilder.withPayload(orderSn).build(), new SendCallback() {
            @Override
            public void onSuccess(SendResult sendResult) {
                if (sendResult.getSendStatus().equals(SendStatus.SEND_OK)) {
                    log.info("发送消息成功");
                }
            }

            @Override
            public void onException(Throwable e) {
                log.error(e.getMessage());
            }
        }, 3000, 16);
        return null;
    }
}
